package com.it.tydic.estate.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileUtil {

	private final static Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static String creatFileName() {
		// ����6λ�����
		int num = 5;
		Random r = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < num; i++) {
			int n = r.nextInt(100);
			sb.append(n);
		}
		Date date = new Date();
		sb.append(date.getTime());
		return sb.toString();
	}

	public static boolean copyFile(String srcFileName, String destFileName, boolean overlay) {
		File srcFile = new File(srcFileName);

		// �ж�Դ�ļ��Ƿ����
		if (!srcFile.exists()) {
			logger.error("�����ļ�ʧ�ܣ�Դ�ļ���" + srcFileName + "������");
			return false;
		} else if (!srcFile.isFile()) {
			logger.error("�����ļ�ʧ�ܣ�Դ�ļ���" + srcFileName + "����һ���ļ���");
			return false;
		}

		// �ж�Ŀ���ļ��Ƿ����
		File destFile = new File(destFileName);
		if (destFile.exists()) {
			// ���Ŀ���ļ����ڲ�������
			if (overlay) {
				// ɾ���Ѿ����ڵ�Ŀ���ļ�������Ŀ���ļ���Ŀ¼���ǵ����ļ�
				new File(destFileName).delete();
			}
		} else {
			// ���Ŀ���ļ�����Ŀ¼�����ڣ��򴴽�Ŀ¼
			if (!destFile.getParentFile().exists()) {
				// Ŀ���ļ�����Ŀ¼������
				if (!destFile.getParentFile().mkdirs()) {
					// �����ļ�ʧ�ܣ�����Ŀ���ļ�����Ŀ¼ʧ��
					return false;
				}
			}
		}

		// �����ļ�
		int byteread = 0; // ��ȡ���ֽ���
		InputStream in = null;
		OutputStream out = null;

		try {
			in = new FileInputStream(srcFile);
			out = new FileOutputStream(destFile);
			byte[] buffer = new byte[1024];

			while ((byteread = in.read(buffer)) != -1) {
				out.write(buffer, 0, byteread);
			}
			return true;
		} catch (FileNotFoundException e) {
			logger.error(e.toString());
			return false;
		} catch (IOException e) {
			logger.error(e.toString());
			return false;
		} finally {
			try {
				if (out != null)
					out.close();
				if (in != null)
					in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// 保存文件
	public static void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		FileOutputStream fs = new FileOutputStream(path + File.separator + filename);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}
	
	@SuppressWarnings({ "unused", "resource" })
	private static void copyFileUsingFileChannels(File source, File dest) {    
		FileChannel input = null;
		FileChannel output = null;
 
		try {
			input = new FileInputStream(source).getChannel();
			output = new FileOutputStream(dest).getChannel();
			output.transferFrom(input, 0, input.size());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (input != null) {
					input.close();
				}
				if (output != null) {
					output.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
}
	public static void writeContentWithFile(File fileName, String content, String charSet) {
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		try {
			if (!fileName.exists()) {
				fileName.createNewFile();
			}
			osw = new OutputStreamWriter(new FileOutputStream(fileName, true), charSet);
			bw = new BufferedWriter(osw);
			bw.write(content);
			bw.newLine();
			bw.flush();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (osw != null) {
				try {
					osw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public static String read(String fileName, String charSet) {
		StringBuilder sb = new StringBuilder();
		String s = "";
		InputStreamReader isr = null;
		BufferedReader bw = null;
		try {
			isr = new InputStreamReader(new FileInputStream(new File(fileName)), charSet);
			bw = new BufferedReader(isr);
			while ((s = bw.readLine()) != null) {
				sb.append(s + "\n");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (isr != null) {
				try {
					isr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println(sb.toString());
		return sb.toString();
	}

	// 方法一
	public static void copyFile1(String srcPath, String destPath) throws IOException {
		// 打开输入流
		FileInputStream fis = new FileInputStream(srcPath);
		// 打开输出流
		FileOutputStream fos = new FileOutputStream(destPath);

		// 读取和写入信息
		int len = 0;
		while ((len = fis.read()) != -1) {
			fos.write(len);
		}

		// 关闭流 先开后关 后开先关
		fos.close(); // 后开先关
		fis.close(); // 先开后关

	}

	// 方法二
	public static void copyFile2(String srcPath, String destPath) throws IOException {

		// 打开输入流
		FileInputStream fis = new FileInputStream(srcPath);
		// 打开输出流
		FileOutputStream fos = new FileOutputStream(destPath);

		// 读取和写入信息
		int len = 0;
		// 创建一个字节数组，当做缓冲区
		byte[] b = new byte[1024];
		while ((len = fis.read(b)) != -1) {
			fos.write(b);
		}

		// 关闭流 先开后关 后开先关
		fos.close(); // 后开先关
		fis.close(); // 先开后关

	}

	// 方法三
	public static void copyFile3(String srcPath, String destPath) throws IOException {

		// 打开输入流
		FileInputStream fis = new FileInputStream(srcPath);
		// 打开输出流
		FileOutputStream fos = new FileOutputStream(destPath);

		// 读取和写入信息
		int len = 0;
		// 创建一个字节数组，当做缓冲区
		byte[] b = new byte[1024];
		while ((len = fis.read(b)) != -1) {
			fos.write(b, 0, len);
		}

		// 关闭流 先开后关 后开先关
		fos.close(); // 后开先关
		fis.close(); // 先开后关

	}

	 public static String download(String urlPath,String savePath,String name) throws Exception {
	        // 构造URL
	        URL url = new URL(urlPath);
	        // 打开连接
	        URLConnection con = url.openConnection();
	        //设置请求超时为5s
	        con.setConnectTimeout(5*1000);
	        // 输入流
	        InputStream is = con.getInputStream();
	        // 1K的数据缓冲
	        byte[] bs = new byte[1024];
	        // 读取到的数据长度
	        int len;
	        // 输出的文件流
	        File sf=new File(savePath);
	        if(!sf.exists()){
	            sf.mkdirs();
	        }
	        OutputStream os = new FileOutputStream(savePath+name);

	        // 开始读取
	        while ((len = is.read(bs)) != -1) {
	            os.write(bs, 0, len);
	        }
	        // 完毕，关闭所有链接
	        os.close();
	        is.close();
	        return name;
	    }

}
